package com.dcivision.dms.client.parser;
     
/*
 * @(#)ACMEIndexParser.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the idential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */

import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

import com.dcivision.dms.client.GlobalIndexTransformation;

/**
 * BizSoftIndexParser -- an application that reads an image index file
 * exported from BizSoft using xml file format.
 * <p>
 * ACME index files have this format:<pre>
 * <descriptor type="Document" layout="1.0">
 *  <set status="0">
 *    <pri_attributes object_handle="" baseclass="Document" class="GOC_MPF" formtype="MEMAPP" l
 *    abel="MEMAPP" creator="scan1" datetimecreated="2003-01-02 12:14:07" indexer="index1"
 *     datetimeindexed="02-01-2003 12:48:22" verifier="" datetimeverified=""/>
 *    <properties>
 *      <propertyset>
 *        <property id="Name" name="Name">//LHAN,JFPN SHEII</property>
 *        <property id="HKID" name="HKID">Membership Application Forni</property>
 *        <property id="EmployerName" name="EmployerName">Membership Application Forni</property>
 *        <property id="FormType" name="FormType">I NNRSEETM</property>
 *      </propertyset>
 *    </properties>
 *    <pages CoverPages="T" CoverPage="T">
 *      <page label="Page 1">A20030102121805908.tif</page>
 *    </pages>
 *  </set>
 * </descriptor>
 * </pre>
 *
    @author          Zoe Shum
    @company         DCIVision Limited
    @creation date   06/09/2003
    @version         $Revision: 1.31.2.1 $
 */
public class BIZSOFTIndexParser implements IndexParser {

  public static final String REVISION = "$Revision: 1.31.2.1 $";


  ContentHandler handler;
  Hashtable confTable = new Hashtable();
 
  // no namespaces required
  String nsu = ""; // NamespaceURI
  String rootElement = "descriptor";
  String indent = "\n    "; // for readability!
  String fieldName = "";
  String fieldValue = "";
  String fieldType = "";
  String loginName="";
  String loginPwd="";
  String rootID="";
  String parentID="";
  
  private static final Log log = LogFactory.getLog(BIZSOFTIndexParser.class);
  public void setConfigTable(Hashtable configTable) {
    this.confTable = configTable;
  }

  public String getLoginName(){
    return this.loginName;
  }

  public String getLoginPwd(){
    return this.loginPwd;
  }

  public String getRootID(){
    return this.rootID;
  }

  public String getParentID(){
    return this.parentID;
  }

  /** Parse the input */
  public void parse(InputSource input) throws IOException, SAXException {
    try { // Get an efficient reader for the file

      // Create an Document node as the root for the output.
      DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
      org.w3c.dom.Document indexFile = docBuilder.parse(input);

      //Xml Writer Declare
      AttributesImpl elementAtt = new AttributesImpl();
      Attributes atts = new AttributesImpl(elementAtt);
      String udfName = "";

      //Get all the field value from xml index file
      String valueReferenceNo = "";
      String valueDescription = "";
      String valueUserDef1 = "";
      String valueUserDef2 = "";
      String valueUserDef3 = "";
      String valueUserDef4 = "";
      String valueUserDef5 = "";
      String valueUserDef6 = "";
      String valueUserDef7 = "";
      String valueUserDef8 = "";
      String valueUserDef9 = "";
      String valueUserDef10 = "";
      String submitSystemWorkflow="false";
      String workflowRecordID="";

      Hashtable hashField = new Hashtable();
      hashField.put(confTable.get(IndexParser.FIELD_REFERENCE_NO), IndexParser.FIELD_REFERENCE_NO);
      hashField.put(confTable.get(IndexParser.FIELD_DESCRIPTION), IndexParser.FIELD_DESCRIPTION);
      hashField.put(confTable.get(IndexParser.FIELD_USER_DEF_1), IndexParser.FIELD_USER_DEF_1);
      hashField.put(confTable.get(IndexParser.FIELD_USER_DEF_2), IndexParser.FIELD_USER_DEF_2);
      hashField.put(confTable.get(IndexParser.FIELD_USER_DEF_3), IndexParser.FIELD_USER_DEF_3);
      hashField.put(confTable.get(IndexParser.FIELD_USER_DEF_4), IndexParser.FIELD_USER_DEF_4);
      hashField.put(confTable.get(IndexParser.FIELD_USER_DEF_5), IndexParser.FIELD_USER_DEF_5);
      hashField.put(confTable.get(IndexParser.FIELD_USER_DEF_6), IndexParser.FIELD_USER_DEF_6);
      hashField.put(confTable.get(IndexParser.FIELD_USER_DEF_7), IndexParser.FIELD_USER_DEF_7);
      hashField.put(confTable.get(IndexParser.FIELD_USER_DEF_8), IndexParser.FIELD_USER_DEF_8);
      hashField.put(confTable.get(IndexParser.FIELD_USER_DEF_9), IndexParser.FIELD_USER_DEF_9);
      hashField.put(confTable.get(IndexParser.FIELD_USER_DEF_10), IndexParser.FIELD_USER_DEF_10);

      /* Variable used for UDF 1st existence parsing */
      String documentProfileName = "";
      boolean haveDocumentProfileChild = false;

      /* Parse Document tag for the use name and login pwd */
      NodeList doclist = indexFile.getElementsByTagName("Document");
      Node docNode = doclist.item(0);
      if (docNode != null) {
        if ("Document".equals(docNode.getNodeName())) {
      
          
          try { loginName = ((Element)docNode).getAttributeNode("loginName").getValue(); } catch (Exception ignore) {}
          try { loginPwd = ((Element)docNode).getAttributeNode("loginPwd").getValue(); } catch (Exception ignore) {}
          try { rootID = ((Element)docNode).getAttributeNode("rootID").getValue(); } catch (Exception ignore) {}
          try { parentID = ((Element)docNode).getAttributeNode("parentID").getValue(); } catch (Exception ignore) {}
        }
      }

      /* Parse IndexTemplate tag for the use name and login pwd */
      NodeList rootlist = indexFile.getElementsByTagName("IndexTemplate");
      Node rootNode = rootlist.item(0).getFirstChild();


      /* To get the first existence of UDF name */
      if ("Folder".equals(rootNode.getNodeName())) {
        if (rootNode != null) {
          documentProfileName = ( (Element)rootNode).getAttributeNode("Name").getValue();
         

            //TEMP Validate
            documentProfileName= documentProfileName.replaceAll("~", "/");
          
          

          //System.out.println("TRACE TEMP, NEED REMOVE LATER : documentProfileName =  " + documentProfileName);
          //End TEMP
        }
      }

      rootNode = rootNode.getFirstChild();
      if (rootNode != null) {
      if ("#text".equals(rootNode.getNodeName())) {

          rootNode = rootNode.getNextSibling();
        }
      }

      /* Looping and Check to see whether have workflow record id or not */
      Node ptr = rootNode;
      while (ptr != null) {
        if ("#text".equals(ptr.getNodeName())) {
          ptr = ptr.getNextSibling();
        }
        if (ptr != null) {
          if ("Workflow".equals( ( (Element)ptr).getAttributeNode("Name").getValue())) {
            submitSystemWorkflow="true";
          }
          ptr = ptr.getNextSibling();
        }
      }
      /*End Workflow checking*/

      /* Start the general looping for attribute and UDF */
      ptr = rootNode;   //reset the pointer into rootNode
      while (ptr != null) {
        if ("#text".equals(ptr.getNodeName())) {
          ptr = ptr.getNextSibling();
        }
        if (ptr != null) {
          if ("Common".equals( ( (Element)ptr).getAttributeNode("Name").getValue())) {
            NodeList attrList = ( (Element)ptr).getElementsByTagName("Folder");
            for (int i = 0; i < attrList.getLength(); i++) {
              Element attr = (Element)attrList.item(i);
              if (com.dcivision.dms.client.parser.IndexParser.FIELD_REFERENCE_NO.equals(hashField.get(attr.getAttributeNode("Name").getValue()))) {
                valueReferenceNo = parseItemValue(attr);
              }else if (com.dcivision.dms.client.parser.IndexParser.FIELD_DESCRIPTION.equals(hashField.get(attr.getAttributeNode("Name").getValue()))) {
                valueDescription = parseItemValue(attr);
              }else if (com.dcivision.dms.client.parser.IndexParser.FIELD_USER_DEF_1.equals(hashField.get(attr.getAttributeNode("Name").getValue()))) {
                valueUserDef1 = parseItemValue(attr);
              }else if (com.dcivision.dms.client.parser.IndexParser.FIELD_USER_DEF_2.equals(hashField.get(attr.getAttributeNode("Name").getValue()))) {
                valueUserDef2 = parseItemValue(attr);
              }else if (com.dcivision.dms.client.parser.IndexParser.FIELD_USER_DEF_3.equals(hashField.get(attr.getAttributeNode("Name").getValue()))) {
                valueUserDef3 = parseItemValue(attr);
              }else if (com.dcivision.dms.client.parser.IndexParser.FIELD_USER_DEF_4.equals(hashField.get(attr.getAttributeNode("Name").getValue()))) {
                valueUserDef4 = parseItemValue(attr);
              }else if (com.dcivision.dms.client.parser.IndexParser.FIELD_USER_DEF_5.equals(hashField.get(attr.getAttributeNode("Name").getValue()))) {
                valueUserDef5 = parseItemValue(attr);
              }else if (com.dcivision.dms.client.parser.IndexParser.FIELD_USER_DEF_6.equals(hashField.get(attr.getAttributeNode("Name").getValue()))) {
                valueUserDef6 = parseItemValue(attr);
              }else if (com.dcivision.dms.client.parser.IndexParser.FIELD_USER_DEF_7.equals(hashField.get(attr.getAttributeNode("Name").getValue()))) {
                valueUserDef7 = parseItemValue(attr);
              }else if (com.dcivision.dms.client.parser.IndexParser.FIELD_USER_DEF_8.equals(hashField.get(attr.getAttributeNode("Name").getValue()))) {
                valueUserDef8 = parseItemValue(attr);
              }else if (com.dcivision.dms.client.parser.IndexParser.FIELD_USER_DEF_9.equals(hashField.get(attr.getAttributeNode("Name").getValue()))) {
                valueUserDef9 = parseItemValue(attr);
              }else if (com.dcivision.dms.client.parser.IndexParser.FIELD_USER_DEF_10.equals(hashField.get(attr.getAttributeNode("Name").getValue()))) {
                valueUserDef10 = parseItemValue(attr);
              }
            }

            //write defaut profile value
            if (handler == null) {
              throw new SAXException("No content handler");
            }
            // Start the document, and write its root element
            handler.startDocument();

            elementAtt.addAttribute("", "", "class", "", "Document");
            //elementAtt.addAttribute("","","name_prefix","","JOS");
            elementAtt.addAttribute("", "", "type", "", ( (String)confTable.get(IndexParser.SCAN_UPLOAD_FILE_EXTEN)).trim());
            elementAtt.addAttribute("", "", "scan_method", "", ( (String)confTable.get(IndexParser.SCAN_METHOD)).trim());
            elementAtt.addAttribute("", "", "submit_system_workflow", "", submitSystemWorkflow);
            if (parentID!=null && !"".equals(parentID)){
              elementAtt.addAttribute("", "", "parent_id", "", parentID);
            }else{
              elementAtt.addAttribute("", "", "parent_id", "", ( (String)confTable.get(IndexParser.DMS_PARENT_ID)).trim());
            } 
            if (rootID!=null && !"".equals(rootID)){
              elementAtt.addAttribute("", "", "root_id", "", rootID);
            }else{
              elementAtt.addAttribute("", "", "root_id", "", ( (String)confTable.get(IndexParser.DMS_ROOT_ID)).trim());
            }

            //Get datetimecreated from index file as the create date
            String datetimecreated = "";
            String createBy = ( (String)confTable.get(IndexParser.LOGIN_NAME)).trim();

            //NodeList nlc = (NodeList)indexFile.getElementsByTagName("pri_attributes");
            //for (int i = 0; i < nl.getLength(); i++) {
            //Element targetNode = (Element)nl.item(i);
            //datetimecreated = targetNode.getAttribute("datetimecreated");
            //log.debug("datetimecreated = "+ datetimecreated);
            //createBy = targetNode.getAttribute("creator");
            //udfName = targetNode.getAttribute("class");
            //log.debug("ame = "+ udfName);
            //}
            elementAtt.addAttribute("", "", "create_date", "", datetimecreated);
            elementAtt.addAttribute("", "", "create_by", "", createBy);
            atts = new AttributesImpl(elementAtt);
            handler.startElement(nsu, rootElement, rootElement, atts);
            //className user for document/folder name creation
            writeTag("class_name", "StandardDocumentAnalyzer.class", new AttributesImpl());

            /*--Start of Default Profile --*/
            writeTag("description", valueDescription, new AttributesImpl());
            writeTag("reference_no", valueReferenceNo, new AttributesImpl());
            writeTag("user_def_1", valueUserDef1, new AttributesImpl());
            writeTag("user_def_2", valueUserDef2, new AttributesImpl());
            writeTag("user_def_3", valueUserDef3, new AttributesImpl());
            writeTag("user_def_4", valueUserDef4, new AttributesImpl());
            writeTag("user_def_5", valueUserDef5, new AttributesImpl());
            writeTag("user_def_6", valueUserDef6, new AttributesImpl());
            writeTag("user_def_7", valueUserDef7, new AttributesImpl());
            writeTag("user_def_8", valueUserDef8, new AttributesImpl());
            writeTag("user_def_9", valueUserDef9, new AttributesImpl());
            writeTag("user_def_10", valueUserDef10, new AttributesImpl());

            /*--End of Default Profile --*/

          } /* Start of UDF Profile */

          else if (ptr.getChildNodes().item(0) == null || ptr.getChildNodes().item(0).getNodeValue() == null || ptr.getChildNodes().item(0).getNodeValue().trim().length() == 0) {
            //Get the workflow record id...if exists
            if ("Workflow".equals( ( (Element)ptr).getAttributeNode("Name").getValue())) {
              NodeList attrList = ( (Element)ptr).getElementsByTagName("Folder");
              for (int i = 0; i < attrList.getLength(); i++) {
                Element attr = (Element)attrList.item(i);
                NodeList itemList = attr.getElementsByTagName("Item");
                String value ="";
                               
                  if(itemList!=null && itemList.getLength() > 0){
	                  Element item = (Element)itemList.item(0);		  			
		                if(item.getChildNodes() != null && item.getChildNodes().getLength() > 0){
          	    	    value = item.getChildNodes().item(0) == null ? "" : item.getChildNodes().item(0).getNodeValue();
                    if (value!=null && value.indexOf(".")>=0){
                      workflowRecordID = value.substring(0, value.indexOf("."));
		                }
		              }
                }
              }
              elementAtt.clear();
              atts = new AttributesImpl(elementAtt);
              writeTag("workflow_record_id", workflowRecordID, atts);
              ptr = ptr.getNextSibling();
              break;
            }

            //UDF Profile value
            /* Commented by Zoe; to amended the parser position for profile Name
             String profileName =  ( (Element)ptr).getAttributeNode("Name").getValue();
             TODO: This will be required to rollback once the muplie profile integration finished
             */
            String profileName = documentProfileName;
//System.out.println(" documentProfileName = " + documentProfileName);
            //replace the "_" for space
            profileName = this.replaceString(profileName, "_", " ");
            elementAtt.clear();
            elementAtt.addAttribute("", "", "name", "", profileName);
            atts = new AttributesImpl(elementAtt);
            
            if(profileName.equals(confTable.get(IndexParser.FIELD_NO_UDF))){
              writeStartTag("document_profile", "", new AttributesImpl());
            }else{
            
          
            writeStartTag("document_profile", "", atts);

            //attribute
            fieldName = "";
            fieldType = "";
            fieldValue = "";
           
              NodeList attrList = ( (Element)ptr).getElementsByTagName("Folder");
              if (attrList.getLength() > 0){
                haveDocumentProfileChild = true;
                for (int i = 0; i < attrList.getLength(); i++) {
                  fieldValue = "";
                  fieldName = "";
                  Element attr = (Element)attrList.item(i);
                  fieldName = attr.getAttributeNode("Name").getValue();

                  //replace the "_" for space
                  fieldName = this.replaceString(fieldName, "_", " ");

                  //Change for field value - item
                  NodeList itemList = attr.getElementsByTagName("Item");
		  if(itemList!=null && itemList.getLength() > 0){
	            Element item = (Element)itemList.item(0);		  			
		    if(item.getChildNodes() != null && item.getChildNodes().getLength() > 0){
          	    	fieldValue = item.getChildNodes().item(0) == null ? "" : item.getChildNodes().item(0).getNodeValue();
		    }
                  }
                  elementAtt.clear();
                  elementAtt.addAttribute("", "", "name", "", fieldName);
                  elementAtt.addAttribute("", "", "type", "", fieldType);
                  atts = new AttributesImpl(elementAtt);
                  writeTag("field", fieldValue, atts);
                }
              }
           
            
            writeEndTag("document_profile");
        
            }//udf
            
            /* End document Profile section*/
          }
          ptr = ptr.getNextSibling();
        }
      }

      //Used for Document Profile with emtpy field
      if (haveDocumentProfileChild == false) {
        String profileName = documentProfileName;
       
          
        //replace the "_" for space
          profileName = this.replaceString(profileName, "_", " ");
          elementAtt.clear();
          elementAtt.addAttribute("", "", "name", "", profileName);
          atts = new AttributesImpl(elementAtt);
          if(profileName.equals(confTable.get(IndexParser.FIELD_NO_UDF))){
            writeStartTag("document_profile", "", new AttributesImpl());
          }else{
         
          writeStartTag("document_profile", "", atts);
          elementAtt.clear();
           elementAtt.addAttribute("", "", "name", "", "");
           elementAtt.addAttribute("", "", "type", "", "");
           atts = new AttributesImpl(elementAtt);
           writeTag("field", "", atts);
        
        
        

        
           }//check for default profile
       writeEndTag("document_profile");
      }

      fieldName = "";
      fieldValue = "";

      /* Pages section*/
      int pagesCount = 0;
      NodeList pagesList = indexFile.getElementsByTagName("page");
      if (pagesList != null)
        pagesCount = pagesList.getLength();
      elementAtt.clear();
      elementAtt.addAttribute("", "", "count", "", new Integer(pagesCount).toString());
      atts = new AttributesImpl(elementAtt);
      writeStartTag("pages", "", atts);

      String label = "";
//      for (int i = 0; i < pagesList.getLength(); i++) {
//        Element targetNode = (Element)pagesList.item(i);
//        label = targetNode.getAttribute("label");
        //get the text as subnode handling
//        Node subnode = pagesList.item(i).getFirstChild();
//        if (subnode != null) {
//          fieldValue = subnode.getNodeValue();
        fieldValue =  ((String)confTable.get(IndexParser.UPLOAD_FILE_FILENAME)).trim();
          //log.debug("value " + subnode.getNodeValue());
//        }
        elementAtt.clear();
        elementAtt.addAttribute("", "", "label", "", label);
        atts = new AttributesImpl(elementAtt);
        writeTag("page", fieldValue, atts);
//      }
      writeEndTag("pages");
      /* End Pages section*/

      /* Index Detail section*/
      int indexFileCount = 1;
      elementAtt.clear();
      elementAtt.addAttribute("", "", "file_count", "", new Integer(indexFileCount).toString());
      atts = new AttributesImpl(elementAtt);
      writeStartTag("index_detail", "", atts);

      String value = "all";
      fieldValue = (String)confTable.get(IndexParser.XML_INDEX_FILENAME);
      fieldValue = fieldValue.substring(1, fieldValue.length());  //clear up the char '\' for presentation
      elementAtt.clear();
      elementAtt.addAttribute("", "", "value", "", value);
      atts = new AttributesImpl(elementAtt);
      writeTag("file", fieldValue, atts);

      writeEndTag("index_detail");
      /* End Index Detail section*/

      /* Full Text section*/
      atts = new AttributesImpl();
//System.out.println("IndexParser.FULL_TEXT = " + (String)confTable.get(IndexParser.FULL_TEXT));
//      fieldValue = (String)confTable.get(IndexParser.FULL_TEXT);
      fieldValue = "";
      writeTag("full_text", fieldValue, atts);

      /* End Full Text section*/

      handler.ignorableWhitespace("\n".toCharArray(),
                                  0, // start index
                                  1 // length
                                  );
      handler.endElement(nsu, rootElement, rootElement);
      handler.endDocument();

    } catch (Exception e) {
      log.error(e, e);
      throw new java.io.IOException(e.getMessage());
    }
  }

  void writeTag(String tagName, String value, Attributes atts) throws SAXException {
    handler.ignorableWhitespace(indent.toCharArray(),
                                0, // start index
                                indent.length()
                                );
    handler.startElement(nsu, tagName, tagName /*"qName"*/, atts);

    handler.characters(value.toCharArray(),
                       0,
                       value.length());
    handler.endElement(nsu, tagName, tagName);
  }

  void writeStartTag(String tagName, String value, Attributes atts) throws SAXException {
    handler.ignorableWhitespace(indent.toCharArray(),
                                0, // start index
                                indent.length()
                                );

    handler.startElement(nsu, tagName, tagName, atts);
  }

  void writeEndTag(String tagName) throws SAXException {
    handler.ignorableWhitespace(indent.toCharArray(),
                                0, // start index
                                indent.length()
                                );
    handler.endElement(nsu, tagName, tagName);
  }

  /** Backup All the target upload files and index files. */
  public void backupAllFiles(String actionStatus) {
    String backupDir = (String)confTable.get(IndexParser.BACKUP_DIR);
    String sourceDir = (String)confTable.get(IndexParser.SOURCE_DIR);
    String errorDir = (String)confTable.get(IndexParser.ERROR_DIR);

    //Target Dir depends on the action is success or error
    String targetDir = backupDir;
    if (GlobalIndexTransformation.STATUS_ERROR.equals(actionStatus)) {
      targetDir = errorDir;
    }
    File backup = new File(targetDir);
    if (!backup.exists()) {
      backup.mkdirs();
    }
    String uploadFilePath = (String)confTable.get(IndexParser.UPLOAD_FILE_PATH);
    this.copyAndDeleteFile(sourceDir, targetDir, uploadFilePath);

    String oldIndexFilePath = (String)confTable.get(IndexParser.OLD_INDEX_FILE_PATH);
    this.copyAndDeleteFile(sourceDir, targetDir, oldIndexFilePath);

    String xmlIndexFilePath = (String)confTable.get(IndexParser.XML_INDEX_FILE_PATH);
    this.copyAndDeleteFile(sourceDir, targetDir, xmlIndexFilePath);
    if (GlobalIndexTransformation.STATUS_ERROR.equals(actionStatus)) {
      this.deleteFile(targetDir, xmlIndexFilePath);
    }

    String fullTextPath = (String)confTable.get(IndexParser.FULL_TEXT_FILE_PATH);
    this.copyAndDeleteFile(sourceDir, targetDir, fullTextPath);
  }

  public void copyAndDeleteFile(String sourceDir, String backupDir, String targetFilePath) {
    String data = "";
    String fileName = "";
    try {
      File inputFile = new File(targetFilePath);
      File ofile = new File(targetFilePath);
      fileName = ofile.getName();
      if (ofile.exists()) {
        java.io.FileInputStream fis = new java.io.FileInputStream(inputFile);
        byte[] content = new byte[1024 * 1024];

        String newFileAbsPath = backupDir + File.separator + fileName;
        File f = new File(newFileAbsPath);
        if (!f.exists()) {
          f.createNewFile();
          java.io.FileOutputStream fos = new java.io.FileOutputStream(f);

          int bufferSize = 8192;
          byte[] buffer = new byte[bufferSize];
          int length = -1;

          while ( (length = fis.read(buffer, 0, bufferSize)) != -1) {
            fos.write(buffer, 0, length);
          }
          fos.flush();
          fos.close();
          fis.close();

        }
        if (f.exists()) {
          fis.close();
          ofile.delete();
        }
      }
    } catch (Exception e) {
      log.error(e, e);
    }
  }

  public void deleteFile(String dir, String targetFilePath) {

    String fileName = "";
    try {
      File file = new File(targetFilePath);
      fileName = file.getName();
      if (file.exists()) {
        file.delete();
      }
    } catch (Exception e) {
      log.error(e, e);
    }
  }

  /** Allow an application to register a content event handler. */
  public void setContentHandler(ContentHandler handler) {
    this.handler = handler;
  }

  /** Return the current content handler. */
  public ContentHandler getContentHandler() {
    return this.handler;
  }

  //=============================================
  // IMPLEMENT THESE FOR A ROBUST APP
  //=============================================
  /** Allow an application to register an error event handler. */
  public void setErrorHandler(ErrorHandler handler) {}

  /** Return the current error handler. */
  public ErrorHandler getErrorHandler() {
    return null;
  }

  //=============================================
  // IGNORE THESE
  //=============================================
  /** Parse an XML document from a system identifier (URI). */
  public void parse(String systemId) throws IOException, SAXException {}

  /** Return the current DTD handler. */
  public DTDHandler getDTDHandler() {
    return null;
  }

  /** Return the current entity resolver. */
  public EntityResolver getEntityResolver() {
    return null;
  }

  /** Allow an application to register an entity resolver. */
  public void setEntityResolver(EntityResolver resolver) {}

  /** Allow an application to register a DTD event handler. */
  public void setDTDHandler(DTDHandler handler) {}

  /** Look up the value of a property. */
  public Object getProperty(String name) {
    return null;
  }

  /** Set the value of a property. */
  public void setProperty(String name, Object value) {}

  /** Set the state of a feature. */
  public void setFeature(String name, boolean value) {}

  /** Look up the value of a feature. */
  public boolean getFeature(String name) {
    return false;
  }

  public String replaceString(String src, String ori, String tar) {
   String result = null;

   if (src!=null && ori!=null && tar!=null){
     try {
       StringBuffer source = new StringBuffer(src);
       int appearedIndex = 0;
       int oriLength = ori.length();
       int tarLength = tar.length();
       int byPassingIndex = 0;
       // If you got exception here, please check your JDK version. JDK 1.4 is needed for this method.
       while (source.indexOf(ori,byPassingIndex)!=-1) {
         appearedIndex = source.indexOf(ori,byPassingIndex);
         if (ori.equals(source.substring(appearedIndex,appearedIndex+oriLength))) {
           source = source.replace(appearedIndex,appearedIndex+oriLength,tar);
           byPassingIndex = appearedIndex+tarLength;
         } else {
           byPassingIndex = appearedIndex;
         }
       }
       result = source.toString();
     } catch (Exception e) {
       log.error(e, e);
     }
   }
   return result;
 }

  private static String parseItemValue(Element attr){ 
    String value = "";    
    NodeList itemList = attr.getElementsByTagName("Item");
    if(itemList!=null && itemList.getLength()>0){
      Element item = (Element)itemList.item(0);
      value = item.getChildNodes().item(0)==null? "" : item.getChildNodes().item(0).getNodeValue();
    }
    return value;
  }
}
